/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities.dao;

import entities.Contentindex;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entities.Post;
import entities.dao.exceptions.IllegalOrphanException;
import entities.dao.exceptions.NonexistentEntityException;
import entities.dao.exceptions.PreexistingEntityException;
import entities.dao.exceptions.RollbackFailureException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author Emmanuel
 */
public class DAOContentindex implements Serializable {

    public DAOContentindex(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Contentindex contentindex) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (contentindex.getPostList() == null) {
            contentindex.setPostList(new ArrayList<Post>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Post> attachedPostList = new ArrayList<Post>();
            for (Post postListPostToAttach : contentindex.getPostList()) {
                postListPostToAttach = em.getReference(postListPostToAttach.getClass(), postListPostToAttach.getPostPK());
                attachedPostList.add(postListPostToAttach);
            }
            contentindex.setPostList(attachedPostList);
            em.persist(contentindex);
            for (Post postListPost : contentindex.getPostList()) {
                Contentindex oldContentindexOfPostListPost = postListPost.getContentindex();
                postListPost.setContentindex(contentindex);
                postListPost = em.merge(postListPost);
                if (oldContentindexOfPostListPost != null) {
                    oldContentindexOfPostListPost.getPostList().remove(postListPost);
                    oldContentindexOfPostListPost = em.merge(oldContentindexOfPostListPost);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findContentindex(contentindex.getId()) != null) {
                throw new PreexistingEntityException("Contentindex " + contentindex + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Contentindex contentindex) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Contentindex persistentContentindex = em.find(Contentindex.class, contentindex.getId());
            List<Post> postListOld = persistentContentindex.getPostList();
            List<Post> postListNew = contentindex.getPostList();
            List<String> illegalOrphanMessages = null;
            for (Post postListOldPost : postListOld) {
                if (!postListNew.contains(postListOldPost)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Post " + postListOldPost + " since its contentindex field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            List<Post> attachedPostListNew = new ArrayList<Post>();
            for (Post postListNewPostToAttach : postListNew) {
                postListNewPostToAttach = em.getReference(postListNewPostToAttach.getClass(), postListNewPostToAttach.getPostPK());
                attachedPostListNew.add(postListNewPostToAttach);
            }
            postListNew = attachedPostListNew;
            contentindex.setPostList(postListNew);
            contentindex = em.merge(contentindex);
            for (Post postListNewPost : postListNew) {
                if (!postListOld.contains(postListNewPost)) {
                    Contentindex oldContentindexOfPostListNewPost = postListNewPost.getContentindex();
                    postListNewPost.setContentindex(contentindex);
                    postListNewPost = em.merge(postListNewPost);
                    if (oldContentindexOfPostListNewPost != null && !oldContentindexOfPostListNewPost.equals(contentindex)) {
                        oldContentindexOfPostListNewPost.getPostList().remove(postListNewPost);
                        oldContentindexOfPostListNewPost = em.merge(oldContentindexOfPostListNewPost);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = contentindex.getId();
                if (findContentindex(id) == null) {
                    throw new NonexistentEntityException("The contentindex with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Contentindex contentindex;
            try {
                contentindex = em.getReference(Contentindex.class, id);
                contentindex.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The contentindex with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Post> postListOrphanCheck = contentindex.getPostList();
            for (Post postListOrphanCheckPost : postListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Contentindex (" + contentindex + ") cannot be destroyed since the Post " + postListOrphanCheckPost + " in its postList field has a non-nullable contentindex field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(contentindex);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Contentindex> findContentindexEntities() {
        return findContentindexEntities(true, -1, -1);
    }

    public List<Contentindex> findContentindexEntities(int maxResults, int firstResult) {
        return findContentindexEntities(false, maxResults, firstResult);
    }

    private List<Contentindex> findContentindexEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Contentindex.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Contentindex findContentindex(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Contentindex.class, id);
        } finally {
            em.close();
        }
    }

    public int getContentindexCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Contentindex> rt = cq.from(Contentindex.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
